/*
 * Copyright (C) 2009 Georgios J. Georgopoulos, All rights reserved.
 * 
 * This is free software; you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 3 of the License, or (at your option) any
 * later version.
 * 
 * This software is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this software; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
 * site: http://www.fsf.org.
 */
package org.gwt.mosaic.xul.server;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.gwt.mosaic.xul.client.ui.Container;
import org.gwt.mosaic.xul.client.ui.Description;
import org.gwt.mosaic.xul.client.ui.Element;
import org.gwt.mosaic.xul.client.ui.Label;
import org.gwt.mosaic.xul.client.ui.Observes;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * 
 * @author georgopoulos.georgios(at)gmail.com
 * 
 */
public class Parser extends DefaultHandler {

  private static final String UI_PACKAGE_PREFIX = "org.gwt.mosaic.xul.client.ui.";

  private int level;
  private Element element;
  private ArrayList<Element> path;

  public Parser(String resource) {
    try {
      path = new ArrayList<Element>();
      parse(resource);
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e.getMessage(), e);
    }
  }

  public Element getRoot() {
    return element;
  }

  private void parse(final String resource) {
    try {
      SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
      InputStream is = getClass().getClassLoader().getResourceAsStream(resource);
      saxParser.parse(is, this);
    } catch (Throwable t) {
      throw new IllegalArgumentException(resource, t);
    }
  }

  @SuppressWarnings("unchecked")
  private void startElement(String name) {
    String classname = UI_PACKAGE_PREFIX
        + Character.toUpperCase(name.charAt(0)) + name.substring(1);
    try {
      Class<?> clazz = Class.forName(classname);
      Element c = (Element) clazz.newInstance();
      if (level > 0) {
        if (c instanceof Observes) {
          List<Observes> list = (List<Observes>) element.getAttributeMap().get(
              Element.OBSERVES_ELEMENT_LIST);
          if (list == null) {
            list = new ArrayList<Observes>();
            element.getAttributeMap().put(Element.OBSERVES_ELEMENT_LIST,
                (Serializable) list);
          }
          list.add((Observes) c);
        } else if (element instanceof Container) {
          ((Container) element).add(c);
        }
        element = c;
      } else if (level == 0) {
        element = c;
      }
      path.add(element);
      ++level;
    } catch (Throwable t) {
      throw new IllegalArgumentException(classname, t);
    }
  }

  private void setAttribute(String name, String value) {
    try {
      Method setter = findMethod(element, name);
      Class<?> type = setter.getParameterTypes()[0];
      Object o = null;
      if (type == String.class) {
        o = value;
      } else if ((type == Integer.TYPE) || ((type == Integer.class))) {
        o = new Integer(value);
      } else if ((type == Boolean.TYPE) || ((type == Boolean.class))) {
        o = new Boolean(value);
      } else if ((type == Character.TYPE) || ((type == Character.class))) {
        o = new Character(value.charAt(0));
      } else {
        throw new IllegalArgumentException(type.getName());
      }
      try {
        setter.invoke(element, o);
      } catch (Throwable t) {
        throw new IllegalArgumentException(name, t);
      }
    } catch (Exception ex) {
      element.getAttributeMap().put(name, value);
    }
  }

  private static final Method findMethod(Object target, String name) {
    name = "set" + Character.toUpperCase(name.charAt(0)) + name.substring(1);
    Method[] methods = target.getClass().getMethods();
    for (int j = 0; j < methods.length; j++) {
      if (name.equals(methods[j].getName())
          && (methods[j].getParameterTypes().length == 1)) {
        return methods[j];
      }
    }
    throw new IllegalArgumentException(name);
  }

  private void characters(String text) {
    if (text.trim().length() > 0) {
      if (element instanceof Container) {
        Label label = new Label();
        label.setValue(text);
        ((Container) element).add(label);
      } else if (element instanceof Description) {
        Description description = (Description) element;
        description.setValue(text, true);
      } else {
        setAttribute("label", text);
      }
    }
  }

  private void endElement() {
    int n = path.size();
    if (n == 1) {
      path = null;
    } else {
      path.remove(n - 1);
      element = path.get(n - 2);
    }
    --level;
  }

  @Override
  public void startElement(String pURI, String pLocalName, String pName,
      Attributes pAttributes) throws SAXException {
    startElement(pName);
    for (int i = 0; i < pAttributes.getLength(); i++) {
      setAttribute(pAttributes.getQName(i), pAttributes.getValue(i));
    }
  }

  @Override
  public void characters(char[] pChars, int pStart, int pLength)
      throws SAXException {
    StringBuffer sb = new StringBuffer(pLength);
    boolean whitespace = false;
    for (int i = 0; i < pLength; i++) {
      char c = pChars[pStart + i];
      if (Character.isWhitespace(c)) {
        if (!whitespace) {
          sb.append(' ');
          whitespace = true;
        }
      } else {
        sb.append(c);
        whitespace = false;
      }
    }
    characters(new String(sb.toString()));
  }

  @Override
  public void endElement(String pURI, String pLocalName, String pName)
      throws SAXException {
    endElement();
  }

  @Override
  public InputSource resolveEntity(String publicId, String systemId)
      throws IOException, SAXException {
    // TODO handle i18n with entities
    String resource = new File(systemId).getName();
    InputStream is = getClass().getClassLoader().getResourceAsStream(resource);
    return new InputSource(is);
  }
}
